<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>仓仓管家 - 人员管理</title>
    <link rel="stylesheet" href="./layui/css/layui.css">
    <script src="./layui/layui.js"></script>
    <style>
        body { overflow-x: hidden; background-color: #f2f3f5; }
        .layui-layout-body { padding: 20px; overflow: auto; }
        .main-container {
            max-width: 1200px; margin: 0 auto;
            background-color: #fff; padding: 20px;
            border-radius: 6px; box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }

        .operation-bar {
            display: flex; flex-wrap: wrap; gap: 10px;
            margin: 0 0 20px 0; padding: 15px;
            background-color: #f9f9f9; border-radius: 4px;
            align-items: center;
        }

        .search-container { flex: 1; min-width: 200px; display: flex; gap: 8px; }
        .search-input { flex: 1; max-width: 300px; }
        .btn-group { display: flex; gap: 8px; }

        .layui-table { margin-top: 20px; width: 100%; border-radius: 4px; }

        .layui-modal {
            z-index: 10005; position: fixed; top: 50%; left: 50%;
            transform: translate(-50%, -50%); width: 90%; max-width: 600px;
            background: #fff; border-radius: 8px; box-shadow: 0 5px 20px rgba(0,0,0,0.15);
            display: none; overflow: hidden;
        }
        .layui-modal-header { padding: 15px 20px; border-bottom: 1px solid #f2f2f2; background: #f8f9fa; }
        .layui-modal-title { font-size: 18px; color: #333; font-weight: 500; }
        .layui-modal-body { padding: 20px; max-height: 70vh; overflow-y: auto; }
        .layui-form-item { margin-bottom: 15px; }
        .layui-form-label { width: 100px; padding: 9px 15px; }
        .layui-input-block { margin-left: 130px; }
        .layui-modal-footer { padding: 12px 20px; border-top: 1px solid #f2f2f2; background: #f8f9fa; text-align: right; }

        .layui-modal-mask { z-index: 10004; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.3); display: none; }

        #pagination { margin-top: 20px; text-align: right; }

        @media screen and (max-width: 768px) {
            .operation-bar { flex-direction: column; align-items: stretch; }
            .search-container, .btn-group { width: 100%; }
            .search-input { max-width: 100%; }
            .btn-group { flex-wrap: wrap; }
            .btn-group .layui-btn { flex: 1; margin-bottom: 5px; }
            .layui-form-label { width: 80px; }
            .layui-input-block { margin-left: 100px; }
        }
        @media screen and (max-width: 480px) {
            .layui-form-item { flex-direction: column; display: flex; }
            .layui-form-label { width: 100%; margin-bottom: 5px; padding: 8px 0; }
            .layui-input-block { margin-left: 0; width: 100%; }
        }
    </style>
</head>
<body class="layui-layout-body">
<div class="main-container">
    <div class="layui-layout layui-layout-admin">
        <div class="layui-header">
            <div class="layui-logo">
                <i class="layui-icon layui-icon-users" style="font-size: 24px; color: #1E9FFF;"></i>
                <span style="margin-left: 5px;">仓仓管家</span>
            </div>
            <ul class="layui-nav layui-layout-left">
                <li class="layui-nav-item">
                    <a href="javascript:;">切换表</a>
                    <dl class="layui-nav-child">
                        <dd><a href="admin_user.html" class="layui-this">人员表</a></dd>
                        <dd><a href="admin-good.html">仓库表</a></dd>
                    </dl>
                </li>
            </ul>
            <ul class="layui-nav layui-layout-right">
                <li class="layui-nav-item"><a href="javascript:;">管理员</a></li>
            </ul>
        </div>

        <div class="layui-body">
            <div class="operation-bar">
                <div class="search-container">
                    <div class="layui-input-inline" style="width: 100%;">
                        <input type="number" id="searchInput" placeholder="输入人员ID搜索(10000-100000)"
                               class="layui-input search-input">
                    </div>
                    <button id="searchBtn" class="layui-btn layui-btn-normal">
                        <i class="layui-icon layui-icon-search"></i> 查询
                    </button>
                </div>
                <div class="btn-group">
                    <button id="addUserBtn" class="layui-btn"><i class="layui-icon layui-icon-addition"></i> 增加</button>
                    <button id="editUserBtn" class="layui-btn layui-btn-warm" disabled><i class="layui-icon layui-icon-edit"></i> 编辑</button>
                    <button id="deleteUserBtn" class="layui-btn layui-btn-danger" disabled><i class="layui-icon layui-icon-delete"></i> 删除</button>
                    <button id="refreshBtn" class="layui-btn layui-btn-primary"><i class="layui-icon layui-icon-refresh"></i> 刷新</button>
                </div>
            </div>

            <table class="layui-table" lay-size="sm" lay-even>
                <thead>
                <tr>
                    <th style="width: 40px;"><input type="checkbox" id="checkAll" lay-skin="primary"></th>
                    <th>人员ID</th>
                    <th>姓名</th>
                    <th>性别</th>
                    <th>账号</th>
                    <th>手机号</th>
                    <th>邮箱</th>
                    <th>创建时间</th>
                </tr>
                </thead>
                <tbody id="userTableBody">
                <tr>
                    <td colspan="8" style="text-align: center; padding: 30px;">
                        <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
                        <span style="margin-left: 10px;">正在加载人员数据...</span>
                    </td>
                </tr>
                </tbody>
            </table>

            <div id="pagination"></div>
        </div>

        <div class="layui-footer">© 仓仓管家 - 人员管理系统</div>
    </div>
</div>

<div id="userModal" class="layui-modal">
    <div class="layui-modal-header">
        <h3 class="layui-modal-title" id="modalTitle">添加人员</h3>
    </div>
    <div class="layui-modal-body">
        <form class="layui-form" lay-filter="userForm">
            <div class="layui-form-item">
                <label class="layui-form-label">人员ID</label>
                <div class="layui-input-block">
                    <input type="number" name="userId" id="userId" required
                           placeholder="10000-100000之间的ID" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="userName" id="userName" required
                           placeholder="请输入姓名" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">性别</label>
                <div class="layui-input-block">
                    <select name="userSex" id="userSex" required>
                        <option value="">请选择</option>
                        <option value="男">男</option>
                        <option value="女">女</option>
                        <option value="其他">其他</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">账号</label>
                <div class="layui-input-block">
                    <input type="number" name="userAccount" id="userAccount" required
                           placeholder="10位数字账号" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">密码</label>
                <div class="layui-input-block">
                    <input type="password" name="userPassword" id="userPassword" required
                           placeholder="6-12位密码" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">手机号</label>
                <div class="layui-input-block">
                    <input type="tel" name="userPhone" id="userPhone" required
                           placeholder="11位手机号" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">邮箱</label>
                <div class="layui-input-block">
                    <input type="text" name="userEmail" id="userEmail" required
                           placeholder="请输入邮箱" class="layui-input">
                </div>
            </div>
        </form>
    </div>
    <div class="layui-modal-footer">
        <button class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
        <button class="layui-btn" lay-submit lay-filter="saveBtn">保存</button>
    </div>
</div>

<div id="modalMask" class="layui-modal-mask"></div>

<script>
    layui.use(['element', 'form', 'layer', 'laypage'], function() {
        const element = layui.element;
        const form = layui.form;
        const layer = layui.layer;
        const laypage = layui.laypage;

        const API_BASE_URL = "http://localhost:8081/user";
        let currentUserId = null;
        let currentPage = 1;
        const pageSize = 10;
        let totalCount = 0;
        let currentSearchId = null;

        // DOM元素
        const userTableBody = document.getElementById('userTableBody');
        const searchInput = document.getElementById('searchInput');
        const addUserBtn = document.getElementById('addUserBtn');
        const editUserBtn = document.getElementById('editUserBtn');
        const deleteUserBtn = document.getElementById('deleteUserBtn');
        const searchBtn = document.getElementById('searchBtn');
        const refreshBtn = document.getElementById('refreshBtn');
        const cancelBtn = document.getElementById('cancelBtn');
        const userModal = document.getElementById('userModal');
        const modalMask = document.getElementById('modalMask');

        // 表单元素 - 修正了字段ID，确保与后端一致
        const userIdInput = document.getElementById('userId');
        const userNameInput = document.getElementById('userName');
        const userSexInput = document.getElementById('userSex');
        const userAccountInput = document.getElementById('userAccount');
        const userPasswordInput = document.getElementById('userPassword');
        const userPhoneInput = document.getElementById('userPhone');
        const userEmailInput = document.getElementById('userEmail');

        // 初始化
        init();

        function init() {
            loadUsers();
            bindEvents();
        }

        function bindEvents() {
            // 增加按钮
            addUserBtn.addEventListener('click', () => {
                currentUserId = null;
                // 重置表单
                userIdInput.value = '';
                userNameInput.value = '';
                userSexInput.value = '';
                userAccountInput.value = '';
                userPasswordInput.value = '';
                userPhoneInput.value = '';
                userEmailInput.value = '';
                // 启用ID输入
                userIdInput.removeAttribute('disabled');
                document.getElementById('modalTitle').textContent = '添加人员';
                openModal();
            });

            // 编辑按钮
            editUserBtn.addEventListener('click', () => {
                if (!currentUserId) {
                    layer.msg('请先选择要编辑的人员', {icon: 3});
                    return;
                }

                fetch(`${API_BASE_URL}/${currentUserId}`)
                    .then(res => {
                        if (!res.ok) {
                            if (res.status === 404) {
                                return Promise.reject('人员不存在');
                            }
                            return Promise.reject('获取数据失败');
                        }
                        return res.json();
                    })
                    .then(data => {
                        if (data.code === 200 && data.data) {
                            const user = data.data;
                            // 填充表单
                            userIdInput.value = user.userId;
                            userNameInput.value = user.userName;
                            userSexInput.value = user.userSex || '';
                            userAccountInput.value = user.userAccount || '';
                            userPasswordInput.value = user.userPassword || '';
                            userPhoneInput.value = user.userPhone || '';
                            userEmailInput.value = user.userEmail || '';
                            // 禁用ID输入
                            userIdInput.setAttribute('disabled', 'disabled');
                            document.getElementById('modalTitle').textContent = '编辑人员';
                            openModal();
                        } else {
                            layer.msg(data.message || '人员不存在', {icon: 2});
                        }
                    })
                    .catch(err => {
                        console.error('编辑失败:', err);
                        layer.msg('加载编辑数据失败: ' + err, {icon: 2});
                    });
            });

            // 删除按钮
            deleteUserBtn.addEventListener('click', () => {
                if (!currentUserId) {
                    layer.msg('请先选择要删除的人员', {icon: 3});
                    return;
                }

                layer.confirm(`确定删除ID为 ${currentUserId} 的人员吗？`, {
                    icon: 3, title: '确认删除'
                }, () => {
                    fetch(`${API_BASE_URL}/${currentUserId}`, {method: 'DELETE'})
                        .then(res => {
                            if (!res.ok) {
                                if (res.status === 404) {
                                    return Promise.reject('人员不存在');
                                }
                                return Promise.reject('删除失败');
                            }
                            return res.json();
                        })
                        .then(data => {
                            if (data.code === 200) {
                                layer.msg('删除成功', {icon: 1});
                                currentUserId = null;
                                updateButtonStates();
                                loadUsers();
                            } else {
                                layer.msg(data.message || '删除失败', {icon: 2});
                            }
                        })
                        .catch(err => {
                            console.error('删除失败:', err);
                            layer.msg('删除失败: ' + err, {icon: 2});
                        });
                });
            });

            // 保存按钮
            form.on('submit(saveBtn)', function() {
                // 1. 手动获取所有表单值
                const formData = {
                    userId: parseInt(userIdInput.value),
                    userName: userNameInput.value.trim(),
                    userSex: userSexInput.value,
                    userAccount: parseInt(userAccountInput.value),
                    userPassword: userPasswordInput.value,
                    userPhone: userPhoneInput.value.trim(),
                    userEmail: userEmailInput.value.trim()
                };

                // 2. 表单验证 - 与后端验证规则保持一致
                let isValid = true;
                if (!formData.userName) {
                    layer.tips('姓名不能为空', userNameInput, {tips: [1, '#FF5722']});
                    isValid = false;
                }
                if (isNaN(formData.userId) || formData.userId < 10000 || formData.userId > 100000) {
                    layer.tips('人员ID必须在10000-100000之间', userIdInput, {tips: [1, '#FF5722']});
                    isValid = false;
                }
                if (!formData.userSex) {
                    layer.tips('请选择性别', userSexInput, {tips: [1, '#FF5722']});
                    isValid = false;
                }
                // 修正账号验证规则，确保是10位数字
                if (isNaN(formData.userAccount) || formData.userAccount < 1000000000 || formData.userAccount > 9999999999) {
                    layer.tips('账号必须是10位数字', userAccountInput, {tips: [1, '#FF5722']});
                    isValid = false;
                }
                if (!formData.userPassword || formData.userPassword.length < 6 || formData.userPassword.length > 12) {
                    layer.tips('密码必须是6-12位', userPasswordInput, {tips: [1, '#FF5722']});
                    isValid = false;
                }
                if (!/^\d{11}$/.test(formData.userPhone)) {
                    layer.tips('手机号必须是11位数字', userPhoneInput, {tips: [1, '#FF5722']});
                    isValid = false;
                }
                if (!/^[\w-]+@[\w-]+\.[a-zA-Z]{2,7}$/.test(formData.userEmail)) {
                    layer.tips('邮箱格式不正确', userEmailInput, {tips: [1, '#FF5722']});
                    isValid = false;
                }

                if (!isValid) return false;

                // 3. 发送请求
                const method = currentUserId ? 'PUT' : 'POST';
                const loading = layer.load(1);

                fetch(API_BASE_URL, {
                    method: method,
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(formData)
                })
                .then(res => {
                    layer.close(loading);
                    if (!res.ok) {
                        if (res.status === 400) {
                            return res.json().then(data => Promise.reject(data.message || '参数错误'));
                        } else if (res.status === 404) {
                            return Promise.reject('人员不存在');
                        }
                        return Promise.reject('操作失败');
                    }
                    return res.json();
                })
                .then(data => {
                    if (data.code === 200) {
                        closeModal();
                        layer.msg(currentUserId ? '更新成功' : '添加成功', {icon: 1});
                        loadUsers();
                    } else {
                        layer.msg(data.message || '操作失败', {icon: 2});
                    }
                })
                .catch(err => {
                    layer.close(loading);
                    console.error('保存失败:', err);
                    layer.msg('操作失败: ' + err, {icon: 2});
                });

                return false;
            });

            // 取消按钮
            cancelBtn.addEventListener('click', closeModal);
            modalMask.addEventListener('click', closeModal);

            // 表格行点击
            userTableBody.addEventListener('click', (e) => {
                const tr = e.target.closest('tr');
                if (!tr || !tr.getAttribute('data-id')) return;

                const userId = parseInt(tr.getAttribute('data-id'));
                const checkbox = tr.querySelector('input[type="checkbox"]');

                // 取消其他选中
                document.querySelectorAll('tbody [type="checkbox"]').forEach(cb => {
                    cb.checked = false;
                });
                // 选中当前行
                checkbox.checked = true;
                form.render('checkbox');

                currentUserId = userId;
                updateButtonStates();
            });

            // 全选
            form.on('checkbox(#checkAll)', function(data) {
                const checked = data.elem.checked;
                document.querySelectorAll('tbody [type="checkbox"]').forEach(cb => {
                    cb.checked = checked;
                });
                form.render('checkbox');

                currentUserId = checked ?
                    (userTableBody.querySelector('tr[data-id]')?.getAttribute('data-id') || null) : null;
                updateButtonStates();
            });

            // 刷新
            refreshBtn.addEventListener('click', () => {
                searchInput.value = '';
                currentSearchId = null;
                currentPage = 1;
                currentUserId = null;
                updateButtonStates();
                loadUsers();
            });

            // 搜索
            searchBtn.addEventListener('click', () => {
                const id = searchInput.value.trim();
                currentSearchId = id ? parseInt(id) : null;
                currentPage = 1;
                loadUsers();
            });

            // 回车键搜索
            searchInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    searchBtn.click();
                }
            });
        }

        // 加载人员列表
        function loadUsers() {
            userTableBody.innerHTML = `
                <tr>
                    <td colspan="8" style="text-align: center; padding: 30px;">
                        <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate"></i>
                        <span style="margin-left: 10px;">正在加载人员数据...</span>
                    </td>
                </tr>
            `;

            let url = API_BASE_URL;
            if (currentSearchId) {
                url = `${API_BASE_URL}/${currentSearchId}`;
            }

            fetch(url)
                .then(res => {
                    if (!res.ok) {
                        if (res.status === 404) {
                            return Promise.reject('未找到该人员');
                        }
                        return Promise.reject('加载失败');
                    }
                    return res.json();
                })
                .then(data => {
                    if (data.code === 200) {
                        const users = currentSearchId ? [data.data] : (data.data || []);
                        totalCount = users.length;
                        renderTable(users);
                        renderPagination();
                    } else {
                        throw new Error(data.message || '获取数据失败');
                    }
                })
                .catch(err => {
                    console.error('加载失败:', err);
                    userTableBody.innerHTML = `
                        <tr>
                            <td colspan="8" style="text-align:center;padding:30px;color:#F56C6C;">
                                <i class="layui-icon layui-icon-error"></i> ${err || '加载失败，请刷新重试'}
                            </td>
                        </tr>
                    `;
                });
        }

        // 渲染表格
        function renderTable(users) {
            if (!users || users.length === 0) {
                userTableBody.innerHTML = `
                    <tr>
                        <td colspan="8" style="text-align:center;padding:30px;">
                            <i class="layui-icon layui-icon-search" style="font-size:24px;color:#ccc;"></i>
                            <p style="margin-top:10px;color:#666;">没有找到匹配的人员</p>
                        </td>
                    </tr>
                `;
                return;
            }

            userTableBody.innerHTML = users.map(user => `
                <tr data-id="${user.userId}">
                    <td><input type="checkbox" name="userCheck" lay-skin="primary"></td>
                    <td>${user.userId}</td>
                    <td>${user.userName}</td>
                    <td>${user.userSex || '-'}</td>
                    <td>${user.userAccount || '-'}</td>
                    <td>${user.userPhone || '-'}</td>
                    <td>${user.userEmail || '-'}</td>
                    <td>${user.createTime ? new Date(user.createTime).toLocaleString() : '-'}</td>
                </tr>
            `).join('');

            form.render('checkbox');
        }

        // 更新按钮状态
        function updateButtonStates() {
            const hasSelected = !!currentUserId;
            editUserBtn.disabled = !hasSelected;
            deleteUserBtn.disabled = !hasSelected;

            if (hasSelected) {
                editUserBtn.classList.remove('layui-btn-disabled');
                deleteUserBtn.classList.remove('layui-btn-disabled');
            } else {
                editUserBtn.classList.add('layui-btn-disabled');
                deleteUserBtn.classList.add('layui-btn-disabled');
            }
        }

        // 打开模态框
        function openModal() {
            userModal.style.display = 'block';
            modalMask.style.display = 'block';
            // 重置错误提示
            document.querySelectorAll('.layui-form-danger').forEach(el => {
                el.classList.remove('layui-form-danger');
            });
        }

        // 关闭模态框
        function closeModal() {
            userModal.style.display = 'none';
            modalMask.style.display = 'none';
        }

        // 渲染分页
        function renderPagination() {
            laypage.render({
                elem: 'pagination',
                count: totalCount,
                limit: pageSize,
                curr: currentPage,
                layout: ['prev', 'page', 'next', 'count'],
                jump: (obj, first) => {
                    if (!first) {
                        currentPage = obj.curr;
                        loadUsers();
                    }
                }
            });
        }
    });
</script>
</body>
</html>